import {
  localData
} from '~/tools/localData';
import {
  checkTool
} from '~/tools/check';
import {
  nav2
} from '~/tools/nav2';
import {
  dsx
} from '~/tools/datax';
import {
  ui
} from '~/tools/ui'

const processTag = 'clipboardHistory'
const mobileReg = new RegExp(checkTool.CommonRegex.mobile),
  orderIdReg = /(订单[0-9a-z]+)|([0-9a-z]{32})/,
  msgNotifyReg = /您有(\d+)条客户消息/
const maxNum = 6

export const clipboard = {
  isValid(text) {
    return this.getMobile(text) || this.getOrderId(text) || this.getMsgNum(text)
  },
  getMobile(text) {
    const match = mobileReg.exec(text)
    if (match) return match[0]
    return null
  },
  getOrderId(text) {
    const match = orderIdReg.exec(text)
    if (match) return match[0]
    return null
  },
  getMsgNum(text) {
    const match = msgNotifyReg.exec(text)
    if (match) return match[0]
    return null
  },
  record(text) {
    text = text.trim()
    const history = localData.get(processTag) || []
    if (history.length >= maxNum) history.pop()
    if (history.findIndex(ele => ele.text == text) < 0)
      history.unshift({
        text,
        time: Date.now()
      })
    localData.set(processTag, history)
  },
  getRecords() {
    return localData.get(processTag) || []
  },
  setProcessed(text) {
    localData.set(processTag, text)
  },
  isProcessed(text) {
    return localData.get(processTag) == text
  },
  act(data) {
    const actionSheet = {}
    let mobile, msgNum, orderId
    if (mobile = clipboard.getMobile(data)) {
      actionSheet.mobileUser = '[查用户] ' + mobile
      actionSheet.mobileOrder = '[查订单] ' + mobile
    }
    if (msgNum = clipboard.getMsgNum(data)) actionSheet.msg = '[去消息列表]'
    if (orderId = clipboard.getOrderId(data)) actionSheet.order = '[查订单] ' + orderId

    if (Object.keys(actionSheet).length == 0) return
    ui.actionSheet(actionSheet, (desc, key) => {
      try {
        this.performAction(key, mobile, msgNum, orderId)
      } catch (e) {
        ui.loading(false)
        console.error(e)
      }
    })
  },
  performAction(key, mobile, msgNum, orderId) {
    if (key == 'mobileUser') {
      ui.loading()
      wx.cloud.callFunction({
        name: 'userCmd',
        data: {
          cmd: 'findUserByMobile',
          mobile,
          field: {
            _id: true
          }
        }
      }).then(res => {
        ui.loading(false)
        const user = res.result
        if (!user || !user._id) return ui.toast(false, '未找到用户')

        nav2.staffEdit('edit', user._id)
      }).catch(err => {
        ui.loading(false)
        console.error(err)
      })
    } else if (key == 'mobileOrder') {
      ui.loading()
      dsx.coll('delivery_addr').where({
          mobile
        }).field({
          _openid: 1
        })
        .get()
        .then(res => {
          ui.loading(false)
          const success = res.data?.length > 0
          ui.toast(success, success ? '即将跳转到订单管理' : '未查到配送电话', () => {
            if (success) nav2.orderList('manage', null, JSON.stringify({
              openId: res.data[0]._openid
            }))
          })
        })
    } else if (key == 'msg') {
      nav2.chatList()
    } else if (key == 'order') {
      nav2.orderList('manage', null, JSON.stringify({
        orderId
      }))
    }
  }
}